package qnb._config.aop;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import qnb.service.impl.SysPowerServiceImpl;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author huangxin
 * @date 2019/6/6-17:28
 */
@Aspect
@Component
public class RedisAop {
    private final Logger log = Logger.getLogger(RedisAop.class);

    private static final List<String> INCLUDE = Arrays.asList(SysPowerServiceImpl.MENU, SysPowerServiceImpl.POWER_CODE, SysPowerServiceImpl.ALL_POWER);

    @Autowired
    private RedisTemplate redisTemplate;

    @After("execution(public * qnb.service.impl.Sys*.update*(..))")
    public void update(JoinPoint jp) throws Throwable {
        Set<String> keys = redisTemplate.keys("*");
        List<String> collect = keys.stream().filter(key-> {
            for (String str : INCLUDE) {
                if (key.startsWith(str)){
                    return true;
                }
            }
            return false;
        }).collect(Collectors.toList());
        redisTemplate.delete(collect);
        log.info("清空redis缓存的权限和菜单");
    }

    @After("execution(public * qnb.service.impl.Sys*.delete*(..))")
    public void delete(JoinPoint jp) throws Throwable {
        Set<String> keys = redisTemplate.keys("*");
        List<String> collect = keys.stream().filter(key-> {
            for (String str : INCLUDE) {
                if (key.startsWith(str)){
                    return true;
                }
            }
            return false;
        }).collect(Collectors.toList());
        redisTemplate.delete(collect);
        log.info("清空redis缓存的权限和菜单");
    }
}
